const whitelist = require("./whitelist")
import config from "../../config/config.js"
import { showToast } from '../toast/toast.js'
import applicationInfo from '../util/applicationInfo.js'
import urlUtil from '../util/urlUtil.js'

console.log(config)
const fetch = async (url = '', data = {}, method = 'GET', loading = true) => {
	const token = uni.getStorageSync('token')

	return new Promise((resolve, reject) => {
		if (loading) {
			uni.showLoading({
				title: '加载中'
			})
		}

		uni.request({
			url: config.baseUrl + url,
			method: method,
			data: data,
			header: {
				"ygj-platform": applicationInfo.platform,
				"ygj-api-ver": config.version,
				"Authorization": token
			},
			success: (res) => {
				console.log(res)
				let data = res.data
				if (data.status === 0) {
					// 系统处理正常
					if (typeof(data.body.status) === 'undefined' || data.body.status === 0) {
						// 业务处理逻辑正常，!important(返回body内容)
						resolve(data.body)
					} else {
						// 业务处理异常
						showToast(data.body.reason)
					}
				} else {
					// 后台报错，系统级别异常
					showToast('系统处理异常:' + data.error)
					// reject(data)
				}
			},
			fail: (err) => {
				// 访问失败，网络及服务器级别异常
				showToast('您的网络调皮了！')
				// reject(err)
			},
			complete: () => {
				if (loading) {
					uni.hideLoading()
				}
			}
		})
	})
}

const get = async (url = '', params = {}, loading = true) => {
	return fetch(url, params, 'GET', loading);
}

const post = async (url = '',params = {}, data = {}, loading = true) => {
	return fetch(urlUtil.getFetchUrl(url, params), data, 'POST', loading);
}

export default {
	get,
	post
}
